package com.xmmj.baselibrary.base.dialog

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.Fragment
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.xmmj.baselibrary.base.activity.mvvm.BaseMvvmActivity
import com.xmmj.baselibrary.base.activity.mvvm.BaseViewModel
import com.xmmj.baselibrary.base.activity.permission.PermissionActivity
import com.xmmj.baselibrary.base.fragment.BaseMvvmFragment
import java.lang.reflect.ParameterizedType

/**
 * 支持MVVM架构的Dialog
 */
abstract class BaseMvvmDialog<V : ViewDataBinding, VM : BaseViewModel<*>> : BaseDialog() {
    lateinit var mDataBinding: V
    lateinit var mViewModel: VM
    lateinit var mContentView: View

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        initViewModel()
        initViewDataBinding(inflater, container)
        observeLiveData()
        return mContentView
    }

    override fun onDestroyView() {
        super.onDestroyView()
        mDataBinding.unbind()
    }

    /**
     * 初始化ViewModel
     */
    private fun initViewModel() {
        val modelClass: Class<*>
        val type = javaClass.genericSuperclass
        modelClass = if (type is ParameterizedType) {
            val modelClassList = type.actualTypeArguments
            if (modelClassList.size > 1) {
                modelClassList[1] as Class<*>
            } else if (modelClassList.size == 1) {
                modelClassList[0] as Class<*>
            } else {
                BaseViewModel::class.java
            }
        } else {
            BaseViewModel::class.java
        }
        //创建ViewModel
        mViewModel = createViewModel<ViewModel>(this, modelClass) as VM
        //添加观察者
        lifecycle.addObserver(mViewModel)
        //添加被观察者
        mViewModel.lifecycleOwner = this
    }

    /**
     * 初始化 DataBinding
     *
     * @param inflater  布局加载器
     * @param container 容器
     */
    private fun initViewDataBinding(inflater: LayoutInflater, container: ViewGroup?) {
        mDataBinding = DataBindingUtil.inflate(inflater, getLayoutId(), container, false)
        mDataBinding.setVariable(getVariableId(), mViewModel)
        mContentView = mDataBinding.root
    }

    /**
     * 观察基础UI事件
     */
    private fun observeLiveData() {
        mViewModel.showLoadingLiveData!!.observe(this) { showLoading(it) }
        mViewModel.hideLoadingLiveData!!.observe(this) { hideLoading() }
        mViewModel.toastLiveData!!.observe(this) { toast(it) }
        mViewModel.reLoginLiveData!!.observe(this) { onReLogin() }
        mViewModel.requestLiveData!!.observe(this) { onRequest() }
        mViewModel.dismissLiveData!!.observe(this) { dismiss() }
        mViewModel.finishRefreshLiveData!!.observe(this) { finishRefresh() }
        mViewModel.finishLoadMoreLiveData!!.observe(this) { finishLoadMore(it) }
        mViewModel.setResultLiveData!!.observe(this) {
            requireActivity().setResult(it.resultCode, it.data)
        }
        mViewModel.showEmptyLiveData!!.observe(this) {
            showEmpty(it.isShow, it.imageId, it.hintText)
        }
        mViewModel.showErrorLiveData!!.observe(this) {
            showError(it.imageId, it.errorText, it.btnText)
        }
        mViewModel.requestPermissionLiveData!!.observe(this) {
            if (requireActivity() is PermissionActivity) {
                (requireActivity() as PermissionActivity).requestPermission(
                    it.permissions,
                    it.successAction,
                    it.cancelAction,
                    it.description
                )
            }
        }
    }

    /**
     * 创建ViewModel
     *
     * @param fragment
     * @param cls
     * @param <T>
     * @return
    </T> */
    private fun <T : ViewModel> createViewModel(fragment: Fragment, cls: Class<*>): T {
        return ViewModelProvider(fragment).get(this.toString(), cls as Class<T>)
    }

    /**
     * 获取model变量id
     */
    abstract fun getVariableId(): Int

    /**
     * 获取布局id
     */
    abstract fun getLayoutId(): Int

    /**
     * 显示
     */
    open fun show(lifecycleOwner: LifecycleOwner) {
        when (lifecycleOwner) {
            is BaseMvvmActivity<*, *> -> {
                super.show(lifecycleOwner.supportFragmentManager, this.javaClass.name)
            }
            is BaseMvvmFragment<*, *> -> {
                super.show(
                    lifecycleOwner.requireActivity().supportFragmentManager,
                    this.javaClass.name
                )
            }
            is BaseMvvmDialog<*, *> -> {
                super.show(
                    lifecycleOwner.requireActivity().supportFragmentManager,
                    this.javaClass.name
                )
            }
        }
    }
}